package cn.wolfcode.shiro;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
public class CrmRealm extends AuthorizingRealm {
	@Autowired
	private IEmployeeService employeeService;
	@Autowired
	private IRoleService roleService;

	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		Employee currentUser = UserContext.getCurrentUser();
		Long id = currentUser.getId();
		// 创建授权信息,用于存储角色对象或权限表达式
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

		if(!currentUser.isAdmin()){
			List<String> expressions = employeeService.selectByEmployeeIdForExpression(id);
			List<String> sns = roleService.selectSnByEmployeeId(id);
			info.addStringPermissions(expressions);
			info.addRoles(sns);
			System.out.println(sns);
		}else {
			info.addStringPermission("*:*");
			info.addRole("admin");
		}
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//通过token获取用户名（用户登录的时候填的）
		String username = (String)token.getPrincipal();
		//判断是否存在数据库
		Employee employee = employeeService.selectByUsernameAndId(username, null);
		if(employee != null){
			if(!employee.isStatus()){
				throw new DisabledAccountException("该账号已被禁用");
			}
			//身份信息，凭证信息，当前realm的名字
			return new SimpleAuthenticationInfo(employee,employee.getPassword(),this.getName());
		}
		//返回值就是查询出来的数据，如果查到这个账号，就应该返回该账号正确的数据，如果查不到，就返回null
		return null;
	}
}
